package com.rongshu.view.login.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.utils.VerificationUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.login.adapter.QuestionFeedbackAdapter;
import com.rongshu.view.login.contract.QuestionFeedbackView;
import com.rongshu.view.login.entity.PasswordLogin;
import com.rongshu.view.login.entity.PictureInfomation;
import com.rongshu.view.login.entity.QuestionFeedback;
import com.rongshu.view.login.entity.ReportClass;
import com.rongshu.view.login.entity.UpLoadImageResult;
import com.rongshu.view.login.presenter.QuestionFeedbackPrensenter;
import com.rongshu.view.userInfo.entity.UpLoadImage;
import com.widget.titlebar.ImmersionBar;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class QuestionFeedbackActivity extends BaseActivity<QuestionFeedbackPrensenter> implements QuestionFeedbackView, QuestionFeedbackAdapter.OnNormalorImageClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.txt_top_function)
    TextView txt_top_function;
    @BindView(R.id.edt_user_suggest)
    EditText edt_user_suggest;
    @BindView(R.id.edt_contact_style)
    EditText edt_contact_style;
    @BindView(R.id.txt_keep_back_contact_style)
    TextView txt_keep_back_contact_style;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    //返回相册集合
    private List<LocalMedia> selectList = new ArrayList<>();
    //图片上传成功返回地址
    private List<UpLoadImageResult.ResponseBean.ImgBean> imgBeanList = null;
    //adapter
    private QuestionFeedbackAdapter mQuestionFeedbackAdapter = null;
    // adapter list
    private List<PictureInfomation> mPictureInfomations = null;
    //type
    private int type = -1;
    //position
    private int position = -1;
    //上传的图片图片集合
    private List<PictureInfomation> mUploadPictureInfomations = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar bar = ImmersionBar.with(this);
        bar.reset().keyboardEnable(true,
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (ImmersionBar.isSupportStatusBarDarkFont()) {//是否支持修改状态栏字体颜色
            bar.statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.color_2c2c2c)  //修改flyme OS状态栏字体颜色
                    .init();  //必须调用方可沉浸式
        } else {
            bar.flymeOSStatusBarFontColor(R.color.black)  //修改flyme OS状态栏字体颜色
                    //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                    .statusBarDarkFont(true, 1.0f)
                    .init();  //必须调用方可沉浸式
        }
        bar.init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_question_feedback_view;
    }

    @Override
    protected void initView() {
        //设置title
        txt_top_title.setText(getString(R.string.feedback));
        txt_top_function.setVisibility(View.VISIBLE);
        txt_top_function.setText(getString(R.string.commit));
        //设置RecyclerView
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        //list
        mPictureInfomations = new ArrayList<>();
        mPictureInfomations.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
        //adapter
        mQuestionFeedbackAdapter = new QuestionFeedbackAdapter(this);
        mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomations);
        //set listener
        mQuestionFeedbackAdapter.setOnNormalorImageClickListener(this);
        //set RecyclerView
        mRecyclerView.setAdapter(mQuestionFeedbackAdapter);
        //pic list
        imgBeanList = new ArrayList<>();
    }

    @Override
    protected void initData() {
        //presenter
        setPresenter(new QuestionFeedbackPrensenter(this), this);
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }


    @OnClick({R.id.layout_back, R.id.txt_top_function})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                showKeyboard(false);
                finish();
                break;
            case R.id.txt_top_function://提交
                //反馈内容，联系方式
                String user_suggest = edt_user_suggest.getText().toString().trim();
                String contact_style = edt_contact_style.getText().toString().trim();
                if (TextUtils.isEmpty(user_suggest)) {
                    toast("请输入反馈内容");
                    return;
                }

                if (TextUtils.isEmpty(contact_style)) {
                    toast("请输入手机号或邮箱");
                    return;
                }

                if (!getAdapterImage().isEmpty()) {
                    uploadImage(getAdapterImage());
                } else {
                    submitFeedback();
                }
                break;
        }
    }

    private void uploadImage(List<PictureInfomation> pictureInfomations) {
        if (pictureInfomations == null) {
            return;
        }
        this.mUploadPictureInfomations = pictureInfomations;
        Map<String, RequestBody> bodyMap = new HashMap<>();
        if (!mUploadPictureInfomations.isEmpty()) {
            for (int i = 0; i < mUploadPictureInfomations.size(); i++) {
                File file = new File(mUploadPictureInfomations.get(i).getImage_path());
                bodyMap.put("file" + i + "\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
            }
            //上传图片
            presenter.postUploadMoreFile(bodyMap);
        }
    }

    private void submitFeedback() {
        //反馈内容，联系方式
        String user_suggest = edt_user_suggest.getText().toString().trim();
        String contact_style = edt_contact_style.getText().toString().trim();
        if (TextUtils.isEmpty(user_suggest)) {
            toast(getString(R.string.question_couple_must_not_empty));
            return;
        }

        if (TextUtils.isEmpty(contact_style)) {
            toast(getString(R.string.contact_style_must_not_empty));
            return;
        } else if (!VerificationUtils.isMobile(contact_style) && !VerificationUtils.isEmail(contact_style)) {
            toast(getString(R.string.the_format_is_wrong));
            return;
        }

        int user_id = 0;
        //获取登录的userid
        PasswordLogin.ResponseBean userInfo = UserInfoUtils.getUserInfo();
        if (userInfo != null) {
            user_id = userInfo.getUser_id();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 1);//1反馈/2举报用户/3举报文章/4举报贴子
        map.put("user_id_to", 0);
        map.put("reporttype", 4); //被举报类型(1色情/2广告/3抄袭/4其他/5无)
        //list
        List<String> stringList = null;
        if (imgBeanList != null) {
            stringList = new ArrayList<>();
            for (UpLoadImageResult.ResponseBean.ImgBean imgBean : imgBeanList) {
                stringList.add(imgBean.getFilePath());
            }
        }
        //body
        ReportClass reportClass = new ReportClass();
        reportClass.setFeedback(user_suggest);
        reportClass.setMobile(contact_style);
        reportClass.setImg(stringList);
        presenter.postReportUser(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("user_id_to"),
                (int) map.get("reporttype"),
                Common.encryptionSign(map),
                reportClass);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    //加载图片到view
                    updateAdapterData(selectList);
                    break;
            }
        }
    }

    public void updateAdapterData(List<LocalMedia> selectList) {
        if (selectList == null) {
            return;
        }
        List<PictureInfomation> pictureInfomations = new ArrayList<>();
        List<PictureInfomation> adapterList = getAdapterImage();
        if (type == QuestionFeedbackAdapter.NORMAL) {
            for (LocalMedia localMedia : selectList) {
                pictureInfomations.add(new PictureInfomation(localMedia.getPath(), QuestionFeedbackAdapter.IMAGE));
            }
            if (adapterList != null) {
                if (adapterList.size() > 0) {
                    pictureInfomations.addAll(getAdapterImage());
                }
            }
            if ((pictureInfomations.size()) < 3) {
                pictureInfomations.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
            }
        } else if (type == QuestionFeedbackAdapter.IMAGE) {
            if (mQuestionFeedbackAdapter != null) {
                pictureInfomations = mQuestionFeedbackAdapter.getPictureInfomationList();
                for (int i = 0; i < pictureInfomations.size(); i++) {
                    if (this.position == i) {
                        pictureInfomations.get(position).setImage_path(selectList.get(0).getPath());
                    }
                }
            }
        }

        if (mQuestionFeedbackAdapter != null) {
            if (type == QuestionFeedbackAdapter.NORMAL) {
                this.mPictureInfomations.clear();
                this.mPictureInfomations = pictureInfomations;
                mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomations);
            }
            mQuestionFeedbackAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 上传图片返回结果
     *
     * @param upLoadImage
     */
    @Override
    public void uploadImageResult(UpLoadImage upLoadImage) {
        if (upLoadImage.getErrCode() == 0) {
            UpLoadImage.ResponseBean bean = upLoadImage.getResponse();
            if (bean != null) {
                List<String> picList = bean.getImgUrl();
                if (!picList.isEmpty()) {
                    for (String path : picList) {
                        UpLoadImageResult.ResponseBean.ImgBean imgBean = new UpLoadImageResult.ResponseBean.ImgBean();
                        imgBean.setFilePath(path);
                        imgBeanList.add(imgBean);
                    }

                    if (imgBeanList != null && mUploadPictureInfomations != null) {
                        if (imgBeanList.size() == mUploadPictureInfomations.size()) {
                            submitFeedback();
                        }
                    }
                }
            }
        } else {
            toast(upLoadImage.getErrMsg());
        }
    }

    @Override
    public void onQuestionFeedback(QuestionFeedback questionFeedback) {
        if (questionFeedback.getErrCode() == 0) {
            toast("提交成功");
            clean();
            onBackPressed();
        } else {
            toast(questionFeedback.getErrMsg());
        }
    }

    //清空数据
    private void clean() {
        edt_user_suggest.setText("");
        edt_contact_style.setText("");
        //清空相册
        List<PictureInfomation> pictureInfomations = new ArrayList<>();
        pictureInfomations.add(new PictureInfomation(null, QuestionFeedbackAdapter.NORMAL));
        if (mQuestionFeedbackAdapter != null) {
            this.mPictureInfomations.clear();
            this.mPictureInfomations = pictureInfomations;
            mQuestionFeedbackAdapter.setPictureInfomationList(mPictureInfomations);
            mQuestionFeedbackAdapter.notifyDataSetChanged();
        }
        //清空返回图片集合
        this.imgBeanList = new ArrayList<>();
        this.mUploadPictureInfomations = new ArrayList<>();
    }


    @Override
    public void onClick(int type, int position) {
        switch (type) {
            case QuestionFeedbackAdapter.NORMAL:
            case QuestionFeedbackAdapter.IMAGE:
                this.type = type;
                this.position = position;
                PictureSelector.create(QuestionFeedbackActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .previewImage(true)
                        .isCamera(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }
    }

    private List<PictureInfomation> getAdapterImage() {
        List<PictureInfomation> mPictureInfomations = new ArrayList<>();
        if (mQuestionFeedbackAdapter != null) {
            for (PictureInfomation p : mQuestionFeedbackAdapter.getPictureInfomationList()) {
                if (p.getImage_type() == QuestionFeedbackAdapter.IMAGE) {
                    mPictureInfomations.add(p);
                }
            }
        }

        return mPictureInfomations;
    }


    @Override
    public void onBackPressed() {
        showKeyboard(false);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PictureFileUtils.deleteCacheDirFile(this);
    }
}
